﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using System.Reflection;

namespace UDS.Management.Data
{
    public class EmbeddedSqlScriptReader
    {
        protected string scriptNamespace;

        public SqlCommand GetScriptCommand(string scriptName, params SqlParameter[] parameters)
        {
            string sqlScript = null;
            string scriptFullName;

            if (string.IsNullOrEmpty(scriptNamespace))
            {
                scriptFullName = scriptName;
            }
            else
            {
                scriptFullName = scriptNamespace + "." + scriptName;
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream(scriptFullName))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    sqlScript = reader.ReadToEnd();
                }
            }
            // Fix up null values in parameters
            foreach (SqlParameter param in parameters)
            {
                if (param.Value == null)
                {
                    param.Value = DBNull.Value;
                }
            }

            SqlCommand cmd = new SqlCommand(sqlScript);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddRange(parameters);
            return cmd;
        }

        public Package.SqlSource GetSqlSource(string scriptName)
        {
            return new Package.SqlSource(scriptName, Assembly.GetCallingAssembly().GetManifestResourceStream(scriptName));
        }
    }
}
